package com.ruoyi.lvlian.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class UniversalConverter implements Converter<Object> {

    @Override
    public Class<Object> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) throws Exception {
        try {
            switch (cellData.getType()) {
                case NUMBER:
                    // 处理数字类型，保留两位小数，并转换为字符串
                    BigDecimal value = cellData.getNumberValue().setScale(2, RoundingMode.HALF_UP);
                    return value.toPlainString();  // 返回字符串形式

                case STRING:
                    String valueStr = cellData.getStringValue();
                    System.out.println(valueStr );
                    return  valueStr ;

                case BOOLEAN:
                    return cellData.getBooleanValue().toString();  // 转换为字符串形式

                default:
                    return cellData.getData().toString();  // 其他类型，直接转为字符串
            }
        } catch (Exception e) {
            // 捕获异常，打印详细的错误信息
            String columnName = contentProperty.getField().getName();
            System.err.println("上传excel类型转换错误 " + columnName
                    + ", with value: " + cellData.toString());
            e.printStackTrace();
            throw e; // 继续抛出异常以便上层处理
        }
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;  // 支持所有类型
    }
}
